var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var articleRouter = require('./routes/article');
var jwt = require('jsonwebtoken');

var session = require('express-session')

var app = express();

//mongodb的连接
require("./tools/conn_mongo")



app.all("*", function (req, res, next) {
  //设置允许跨域的域名，*代表允许任意域名跨域
  res.header("Access-Control-Allow-Origin", "*");
  //允许的header类型
  res.header("Access-Control-Allow-Headers", "Content-type,Content-Length,Authorization,Accept,X-Requested-Width");
  //跨域允许的请求方式 
  res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
  res.header("Access-Control-Request-Headers: Origin, X-Requested-With, content-Type, Accept, Authorization");
  if (req.method.toLowerCase() == 'options')
    res.send(200); //让options尝试请求快速结束
  else
    next();
})



//添加拦截器
app.use(function (req, res, next) {
  // 获取请求头中的Authorization认证字符
  if (req.path === '/users/login') {
    next()
  } else if (req.path === '/users/regist') {
    next();
  } else if (req.headers.accept.indexOf('image') == 0) {
    next();
  } else {
    if (req.get('Authorization') == null) {
      res.status(403).send('认证无效，请重新登录。');
    }
    let authorization = req.get('Authorization').split(' ')[1]
    let secretOrPrivateKey = "This is perfect projects.";
    jwt.verify(authorization, secretOrPrivateKey, function (err, decode) {
      if (err) { //  认证出错
        res.status(403).send('认证无效，请重新登录。');
      } else {
        req.query.userInfo = decode
        next();
      } 
    })
  }
})


app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/article', articleRouter)

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler


module.exports = app;